package org.looom.orglooomschool;

import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Handler;
import android.os.IBinder;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;

import org.looom.orglooomschool.service.MusicService9;

public class MainActivity9 extends AppCompatActivity {

    private ImageView imgMusic;
    private SeekBar seekBar;
    private TextView nowTime, totalTime;
    private Button btnPlay, btnPause, btnContinue, btnExit;

    private MusicService9 musicService;
    private boolean isBound = false;
    private Handler handler = new Handler();
    private Runnable updateRunnable;

    private ObjectAnimator rotationAnimator;

    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            musicService = ((MusicService9.LocalBinder) service).getService();
            isBound = true;
            setupUI();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            isBound = false;
        }
    };

    private void setupUI() {
        int duration = musicService.getDuration();
        seekBar.setMax(duration);
        totalTime.setText(formatTime(duration));

        updateRunnable = new Runnable() {
            @Override
            public void run() {
                if (musicService != null && musicService.isPlaying()) {
                    int position = musicService.getCurrentPosition();
                    seekBar.setProgress(position);
                    nowTime.setText(formatTime(position));
                }
                handler.postDelayed(this, 1000);
            }
        };
        handler.post(updateRunnable);
    }

    private String formatTime(int milliseconds) {
        int mins = milliseconds / 1000 / 60;
        int secs = (milliseconds / 1000) % 60;
        return String.format("%02d:%02d", mins, secs);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_9);

        imgMusic = findViewById(R.id.img_music);
        seekBar = findViewById(R.id.seekbar);
        nowTime = findViewById(R.id.nowtime);
        totalTime = findViewById(R.id.totaltime);
        btnPlay = findViewById(R.id.btn_play);
        btnPause = findViewById(R.id.btn_pause);
        btnContinue = findViewById(R.id.btn_continue);
        btnExit = findViewById(R.id.btn_exit);

        Intent intent = new Intent(this, MusicService9.class);
        startService(intent);
        bindService(intent, serviceConnection, BIND_AUTO_CREATE);

        btnPlay.setOnClickListener(v -> {
            if (isBound) {
                musicService.play();
                rotationAnimator.start();
            }
        });

        btnPause.setOnClickListener(v -> {
            if (isBound) {
                musicService.pause();
                rotationAnimator.pause();
            }
        });

        btnContinue.setOnClickListener(v -> {
            if (isBound) {
                musicService.continuePlay();
                rotationAnimator.resume();
            }
        });

        btnExit.setOnClickListener(v -> {
            if (isBound) {
                unbindService(serviceConnection);
                isBound = false;
            }
            stopService(new Intent(this, MusicService9.class));
            finish();
        });

        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser && isBound) {
                    musicService.seekTo(progress);
                }
            }
            @Override public void onStartTrackingTouch(SeekBar seekBar) {}
            @Override public void onStopTrackingTouch(SeekBar seekBar) {}
        });

        // 头像旋转动画
        rotationAnimator = ObjectAnimator.ofFloat(imgMusic, "rotation", 0f, 360f);
        rotationAnimator.setDuration(10000);
        rotationAnimator.setRepeatCount(ValueAnimator.INFINITE);
        rotationAnimator.setInterpolator(new LinearInterpolator());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (isBound) {
            unbindService(serviceConnection);
        }
        handler.removeCallbacks(updateRunnable);
    }
}
